package com.probox.common.core.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.util.StringUtil;
import com.probox.common.core.enums.PlanStatusEnum;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.text.Convert;
import com.probox.common.core.utils.money.MoneyUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * 时间工具类
 *
 * @author usoft
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYYMMDD = "yyyyMMdd";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String HH_MM = "HH:mm";

    public static String HH_MM_SS = "HH:mm:ss";

    public static String HH = "HH";

    public static String mm = "mm";
    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static String getDateM() {
        return dateTimeNow(YYYY_MM);
    }

    public static String getDateT() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final int parseDateToInt(final String format, final Date date) {
        String format1 = new SimpleDateFormat(format).format(date);
        return Convert.toInt(format1, 0);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    public static final String chineseDateTime(Date date) {
        if (date == null) {
            return "";
        }
        return DateFormatUtils.format(date, "y年M月d日");
    }

    public static final String chineseDate(Date date) {
        if (date == null) {
            return "";
        }
        return DateFormatUtils.format(date, "M月d日");
    }

    public static final String shortHourMinute(Date date) {
        if (date == null) {
            return "";
        }
        return DateFormatUtils.format(date, "HH:mm");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    public static final String dateTimeDay() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy-MM-dd");
    }

    public static final String dateTimeY() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    //新增
    public static long diff(String startDate, String endDate) {
        java.text.DateFormat today = new SimpleDateFormat("yyyy-MM-dd");
        long hour = 0;
        try {
            Date start = today.parse(startDate);
            Date end = today.parse(endDate);
            hour = (end.getTime() - start.getTime()) / 1000 / 60 / 60;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return hour;
    }

    public static String formate(Date date) {
        if (date == null) return "";
        java.text.DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(date);
    }

    public static String formate(Date date,String fmt) {
        if (date == null) return "";
        java.text.DateFormat df = new SimpleDateFormat(fmt);
        return df.format(date);
    }

    public static String formate(String date) {
        if (date == null) return "";
        Date time = new Date(date);
        java.text.DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(time);
    }


    public static String formateMinute(Date date) {
        if (date == null) return null;
        java.text.DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return df.format(date);
    }

    public static String formateForOrderNo() {
        java.text.DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
        return df.format(new Date());
    }

    public static String formateToday(Date date) {
        if (date == null) return "";
        java.text.DateFormat today = new SimpleDateFormat("yyyy-MM-dd");
        return today.format(date);
    }

    public static String formateMonth(Date date) {
        if (date == null) return "";
        java.text.DateFormat today = new SimpleDateFormat("yyyy-MM");
        return today.format(date);
    }

    public static String formatTime(Time time) {
        if (time == null) return "";
        DateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(time);
    }

    public static String formatTimes(Date time) {
        if (time == null) return "";
        DateFormat format = new SimpleDateFormat("HH:mm:ss");
        return format.format(time);
    }

    public static String formatTime(Date date) {
        String formatTime = "";
        if (date == null) return formatTime;
        Date currentDate = new Date();
        boolean isToday = org.apache.commons.lang3.time.DateUtils.isSameDay(date, currentDate);
        if (isToday) {
            Long currentTime = currentDate.getTime();
            Long dateTime = date.getTime();
            Long diff = currentTime - dateTime;
            if (diff < 60 * 1000) {
                formatTime = "刚刚";
            } else if (diff < 60 * 60 * 1000) {
                long diffmunite = diff / 60 / 1000;
                formatTime = diffmunite + "分钟内";
            } else if (diff < 24 * 60 * 60 * 1000) {
                formatTime = "今天 " + DateFormatUtils.format(date, "HH:mm");
            }
        } else {
            formatTime = DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatTime;
    }

    public static String formatTimeStr(Date date) {
        String formatTime = "";
        if (date == null) return formatTime;
        Date currentDate = new Date();
        boolean isToday = org.apache.commons.lang3.time.DateUtils.isSameDay(date, currentDate);
        if (isToday) {
            Long currentTime = currentDate.getTime();
            Long dateTime = date.getTime();
            Long diff = currentTime - dateTime;
            long diffmunite = 0;
            if (diff < 60 * 1000) {
                diffmunite = diff / 1000;
                formatTime = diffmunite + "秒前";
            } else if (diff < 60 * 60 * 1000) {
                diffmunite = diff / 60 / 1000;
                formatTime = diffmunite + "分钟前";
            } else if (diff < 24 * 60 * 60 * 1000) {
                diffmunite = diff / 60 / 60 / 1000;
                formatTime = diffmunite + "小时前";
            }
        } else {
            formatTime = DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatTime;
    }


    public static Long getTodayReamminSec() {
        Date date = org.apache.commons.lang3.time.DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
        date = org.apache.commons.lang3.time.DateUtils.addDays(date, 1);
        long remainSec = (date.getTime() - System.currentTimeMillis()) / 1000;
        return remainSec;
    }

    public static boolean beforeDay(Date date) {
        if (date == null) {
            return false;
        }
        Date now = new Date();
        Date roundDate = org.apache.commons.lang3.time.DateUtils.addDays(org.apache.commons.lang3.time.DateUtils.truncate(date, Calendar.DAY_OF_MONTH), 1);
        return now.before(roundDate);
    }

    public static boolean beforeDay(Date now, Date date) {
        if (date == null) {
            return false;
        }
        Date roundDate = org.apache.commons.lang3.time.DateUtils.addDays(org.apache.commons.lang3.time.DateUtils.truncate(date, Calendar.DAY_OF_MONTH), 1);
        return now.before(roundDate);
    }

    public static boolean afterDay(Date date) {
        if (date == null) {
            return false;
        }
        Date now = new Date();
        return now.after(date);
    }

    public static Date parseStrToDate(String strDate, final String partter) {
        java.text.DateFormat df = null;
        if (StringUtil.isEmpty(strDate) || StringUtil.isEmpty(partter))
            df = new SimpleDateFormat("yyyy-MM-dd");
        else
            df = new SimpleDateFormat(partter);

        try {
            return df.parse(strDate);
        } catch (ParseException e) {
            return null;
        }

    }

    public static String currentTimeSeconds() {
        String seconds = String.valueOf(System.currentTimeMillis());
        seconds = seconds.substring(0, seconds.length() - 3);
        return seconds;
    }

    public static String getYMdHms(Date date) {
        if (null == date) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        return format.format(date);
    }

    public static Date getYMdHms(String str) {
        if (null == str) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            return format.parse(str);
        } catch (ParseException e) {
        }
        return null;
    }

    public static Date getYMd(String str) {
        if (null == str) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return format.parse(str);
        } catch (ParseException e) {
        }
        return null;
    }

    public static Date add(Long minute) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MINUTE, minute.intValue());
        return cal.getTime();
    }


    public static Date addDay(Date source, int day) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(source);
        cal.add(Calendar.DAY_OF_MONTH, day);
        return cal.getTime();
    }

    public static Date startAddDay(Date source, int day) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(source);
        cal.add(Calendar.DAY_OF_MONTH, day);
        return dateTime(YYYY_MM_DD_HH_MM_SS, formateToday(cal.getTime()) + " 00:00:00");
    }

    public static Date endAddDay(Date source, int day) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(source);
        cal.add(Calendar.DAY_OF_MONTH, day);
        return dateTime(YYYY_MM_DD_HH_MM_SS, formateToday(cal.getTime()) + " 23:59:59");
    }

    public static Date add(Date source, Long minute) {
        if (minute == null) minute = 0L;
        Calendar cal = Calendar.getInstance();
        cal.setTime(source);
        cal.add(Calendar.MINUTE, minute.intValue());
        Date date = cal.getTime();
        return date;
    }


    public static String formatExpire(Date date) {
        if (null == date) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        return format.format(date);
    }

    public static Date parse(String strDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(strDate);
    }

    public static Date parseTime(String strDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.parse(strDate);
    }

    public static int getAge(Date birthDay) {
        Calendar cal = Calendar.getInstance();
        if (ObjectUtil.isEmpty(birthDay)) return 0;
        if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            return 0;
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age;
    }

    /**
     * 获取某年第一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static Date getYearFirst(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    public static int getYear() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 获取某年最后一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static Date getYearLast(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();

        return currYearLast;
    }


    /**
     * 默认日期格式
     */
    public static String DEFAULT_FORMAT = "yyyy-MM-dd";


    /**
     * 格式化日期
     *
     * @param date 日期对象
     * @return String 日期字符串
     */
    public static String formatDate(Date date) {
        SimpleDateFormat f = new SimpleDateFormat(DEFAULT_FORMAT);
        String sDate = f.format(date);
        return sDate;
    }


    public static String newDateStart() {
        return getDate() + " 00:00:00";
    }

    public static String endDateStart() {
        return getDate() + " 23:59:59";
    }


    /**
     * 校验身份证
     *
     * @param idCard
     */
    public static void getSexFromIdCard(String idCard) {
        int length = idCard.length();
        if (length != 15 && length != 18) {
            throw new BaseException("身份证号有误！");
        }
        int year = 0;
        int month = 0;
        int day = 0;
        //正则匹配身份证号是否是正确的，15位或者17位数字+数字/x/X
        if (idCard.matches("^\\d{15}|\\d{17}[\\dxX]$")) {
            year = Convert.toInt(idCard.substring(6, 10));
            month = Convert.toInt(idCard.substring(10, 12));
            day = Convert.toInt(idCard.substring(12, 14));
            //校验年
            int maxDate = Convert.toInt(getDate().substring(0, 4));
            if (1900 > year || year > maxDate || year == 0) {
                throw new BaseException("身份证号有误！");
            }
            if (month < 1 || month > 12) {//校验月份格式
                throw new BaseException("身份证号有误！");
            }
            if (day < 1 || day > 31) {//校验天数格式
                throw new BaseException("身份证号有误！");
            }
            if ((month == 4 || month == 6 || month == 9 || month == 11) && (day == 31)) {//是否不符合4月、6月、9月、11月最大天数30日
                throw new BaseException("身份证号有误！");
            }
            boolean leap = false;
            if (month == 2) {//闰年2月为29天，平年2月为28天
                leap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
                if (day > 29 || (day == 29 && !leap)) {
                    throw new BaseException("身份证号有误！");
                }
            }
        } else {
            throw new BaseException("身份证号有误！");
        }
    }

    public static List<String> getSevenDate() {

        List<String> dateList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        for (int i = 0; i < 7; i++) {

            Date date = DateUtils.addDays(new Date(), -i);
            String formatDate = sdf.format(date);
            dateList.add(formatDate);
        }
        Collections.reverse(dateList);
        return dateList;
    }


    public static List<LocalDate> getAllDatesInTheDateRange(LocalDate startDate, LocalDate endDate) {
        List<LocalDate> localDateList = new ArrayList<>();
        // 开始时间必须小于结束时间
        if (startDate.isAfter(endDate)) {
            return null;
        }
        while (startDate.isBefore(endDate)) {
            localDateList.add(startDate);
            startDate = startDate.plusDays(1);
        }
        localDateList.add(endDate);
        return localDateList;
    }

//    public static void main(String[] args) {
//
//       System.out.println(MoneyUtils.changeF2B(19L));
//
//    }

}
